package com.nashuju.web.controller.sw;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.groups.Default;

import org.durcframework.core.DefaultGridResult;
import org.durcframework.core.GridResult;
import org.durcframework.core.MessageResult;
import org.durcframework.core.controller.CrudController;
import org.durcframework.core.expression.ExpressionQuery;

import com.google.gson.Gson;
import com.nashuju.app.api.JPush;
import com.nashuju.app.entity.MessageReqBean;
import com.nashuju.app.entity.Msg;
import com.nashuju.web.common.Config;
import com.nashuju.web.entity.sw.RUser;
import com.nashuju.web.entity.sw.RUserSch;
import com.nashuju.web.entity.sw.SCustomer;
import com.nashuju.web.entity.sw.SCustomerSch;
import com.nashuju.web.entity.sw.SMessage;
import com.nashuju.web.entity.sw.SMessageSch;
import com.nashuju.web.entity.sw.STaskSchedule;
import com.nashuju.web.entity.sw.STaskScheduleSch;
import com.nashuju.web.entity.sys.SysUpload;
import com.nashuju.web.entity.sys.SysUploadSch;
import com.nashuju.web.service.sw.RUserService;
import com.nashuju.web.service.sw.SCustomerService;
import com.nashuju.web.service.sw.SMessageService;
import com.nashuju.web.service.sw.STaskScheduleService;
import com.nashuju.web.service.sys.SysUploadService;
import com.nashuju.web.service.user.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class STaskScheduleController extends
		CrudController<STaskSchedule, STaskScheduleService> {
@Autowired
private RUserService rUserService;
@Autowired
private SCustomerService SCustomerService;
@Autowired
private SysUploadService sysUploadService;
@Autowired
private SMessageService SMessageService;


		//新增记录
	@RequestMapping("/addSTaskSchedule.do")
	public @ResponseBody
	MessageResult addSTaskSchedule(STaskSchedule entity) {
		if (entity.getId() != null) {
			STaskScheduleSch searchEntitySch = new STaskScheduleSch();
			searchEntitySch.setIdSch(entity.getId());
			STaskSchedule entity1 = this.getService().find(ExpressionQuery.buildQueryAll().addAnnotionExpression(searchEntitySch)).get(0);
			if(entity1!=null)
			this.update(entity);
			return success("任务更新成功！");
		};
		entity.setStatus(Config.TOBESEND);
		this.save(entity);
		// 添加工作单号和工时
		entity.setTaskNum(Config.TASKNUM+(entity.getId()));
		try
		{
		    Date dfinish = entity.getPlanFinishTime();
		    Date darrive = entity.getPlanArriveTime();
		    long diff = dfinish.getTime() - darrive.getTime();
		    long hours = diff  / (1000 * 60 * 60);
		    entity.setRealWorkTime(String.valueOf(hours));
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		this.update(entity);
		
		RUser userEntity = rUserService.get(entity.getUserId());
		String userName = userEntity.getTrueName();
		SMessage message = new SMessage();
		message.setWorkRecord(userName +"在"+ entity.getEditedTime()+" 添加了任务"+ entity.getTaskNum());
		SMessageService.save(message);
		return  success("任务添加成功，请绑定合同和起始地址！");
	}
	
	//新增记录
	// 这个接口接收很多种情况的请求，并且会根据状态的不同做出不同的处理大多是根据现有的状态更新到下一个状态
	// 主要的功能是发布任务，在发布任务的时候检测用户是否登录，如果登录则直接推送任务，如果没有登录则存储要推送的消息，下次用户登录的时候一并登录
	@RequestMapping("/releaseSTaskSchedule.do")
	public @ResponseBody
	MessageResult releaseSTaskSchedule(STaskSchedule entity) {
		if (entity.getId() != null) {
			STaskScheduleSch searchEntitySch = new STaskScheduleSch();
			searchEntitySch.setIdSch(entity.getId());
			STaskSchedule entity1 = this.getService().find(ExpressionQuery.buildQueryAll().addAnnotionExpression(searchEntitySch)).get(0);
			if(entity1!=null)
			{
				switch (entity1.getStatus()) {
				case "待发布":
					entity.setStatus(Config.RELEASED);
					this.update(entity);
					RUser user = rUserService.get(entity.getExecutorId());
					SMessage message = new SMessage();
					message.setTaskId(entity.getId());
					message.setDestination(entity.getArriveCity());
					message.setShortName(entity.getTaskName());
					message.setTaskNum(entity.getTaskNum());
					message.setTaskType(entity.getTaskType());
					message.setTime(entity.getArriveTime());
					message.setUsername(user.getTrueName());
					message.setTingsToDo(entity.getIssueReason());
					message.setMessage("有任务请查看！");
					String alertMessage = "您在"
							+entity.getArriveTime().getMonth() + "-"
							+entity.getArriveTime().getMonth() + "-"
							+entity.getArriveTime().getDay() + "-"
							+"有"
							+entity.getTaskType()+"任务，请及时查看！";
					
					if (user.getBundleId()!=null && user.getIsLogin().equals(true) ) {
						JPush.alertByRegistrationId(user.getBundleId(), alertMessage,new Gson().toJson(message));
						JPush.alertByRegistrationIdForiOS(user.getBundleId(),alertMessage,entity.getId());
						SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						message.setWorkRecord(user.getTrueName() 
									+"在"
									+ formatter.format(entity.getEditedTime()).toString()
									+" 发布了任务"
									+ entity.getTaskNum());
						message.setReceiveId(entity.getExecutorId());
						message.setStatus("sent");
						message.setSendType("Jpush");
						message.setTaskId(entity.getId());
						SMessageService.save(message);
					}
					return success("任务更新成功 ,且已发布！");
				case "已完成":
					entity.setStatus(Config.VISITED);
					this.update(entity);
					return success("任务已回访！");
				case "已回访":
					entity.setStatus(Config.CHECKED);
					this.update(entity);
					return success("任务已审核通过！");
				case "已审核":
					entity.setStatus(Config.ARCHIVE);
					this.update(entity);
					return success("任务已归档！");
				default:
					this.update(entity);
					return success("任务更新成功！");
				}
				
			}
			
		};
		RUser user = rUserService.get(entity.getExecutorId());
		entity.setSendTime(new Date(System.currentTimeMillis()));
		entity.setStatus(Config.RELEASED);
		SMessage message = new SMessage();
		try {
			this.save(entity);
			if (user.getBundleId()!=null) {
				message.setTaskId(entity.getId());
				message.setDestination(entity.getArriveCity());
				message.setShortName(entity.getShortName());
				message.setTaskNum(entity.getTaskNum());
				message.setShortName(entity.getTaskName());
				message.setTaskType(entity.getTaskType());
				message.setTime(entity.getArriveTime());
				message.setUsername(user.getTrueName());
				message.setTingsToDo(entity.getIssueReason());
				message.setMessage("有任务请查看！");
				String alertMessage = "您在"
						+entity.getPlanArriveTime().getMonth() + "-"
						+entity.getPlanArriveTime().getMonth() + "-"
						+entity.getPlanArriveTime().getDay() + "-"
						+"有"
						+entity.getTaskType()+"任务，请及时查看！";
				
				if (user.getBundleId()!=null) {
					if(user.getIsLogin())
					{
							JPush.alertByRegistrationId(user.getBundleId(), alertMessage,new Gson().toJson(message));
							JPush.alertByRegistrationIdForiOS(user.getBundleId(),alertMessage,entity.getId());
							message.setStatus("sent");
					}
					else 
					{
						message.setStatus("unsent");
					}
				}
			}
		} catch (Exception e) 
		{
			e.printStackTrace();
			return	error("任务添加失败，错误原因："+e.getMessage());
		}
		entity.setTaskNum(Config.TASKNUM+(entity.getId()));
		try
		{
		    Date dfinish = entity.getPlanFinishTime();
		    Date darrive = entity.getPlanArriveTime();
		    long diff = dfinish.getTime() - darrive.getTime();
		    long hours = diff *8 / (1000 * 60 * 60 * 24);
		    entity.setRealWorkTime(String.valueOf(hours));
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		this.update(entity);
		RUser userEntity = rUserService.get(entity.getUserId());
		String userName = userEntity.getTrueName();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		message.setWorkRecord(userName 
				+"在"
				+formatter.format(entity.getEditedTime()).toString()
				+" 发布了任务"
				+ entity.getTaskNum());
		message.setReceiveId(entity.getExecutorId());
		message.setSendType("Jpush");
		SMessageService.save(message);
		return success("新任务发布成功!");
	}

	//删除记录
	@RequestMapping("/delSTaskSchedule.do")
	public @ResponseBody
	MessageResult delSTaskSchedule(STaskSchedule entity) {
		return this.delete(entity);
	}
	
	//修改记录
	@RequestMapping("/updateSTaskSchedule.do")
	public @ResponseBody
	MessageResult updateSTaskSchedule(STaskSchedule entity) {
		SMessage message = new SMessage();
		message.setWorkRecord(entity.getCreatePerson() +"在"+ entity.getEditedTime()+" 更新了工单"+ entity.getTaskNum() +"的内容");
		SMessageService.save(message);
		return this.update(entity);
	}
	

	//条件查询分页操作
	@RequestMapping("/listSTaskSchedule.do")
	public @ResponseBody
	GridResult listSTaskSchedule(STaskScheduleSch searchEntitySch) throws UnsupportedEncodingException {
		if (searchEntitySch.getStatusSch()!=null) {
			searchEntitySch.setStatusSch(URLDecoder.decode(searchEntitySch.getStatusSch(), "UTF-8"));
		}

		DefaultGridResult Result= (DefaultGridResult) this.query(searchEntitySch);
		List<STaskSchedule> taskSchedules = (List<STaskSchedule>) Result.getRows();
		Result.setList(taskSchedules);
		try {
		
		for (STaskSchedule sTaskSchedule : taskSchedules) {
			RUserSch userSch =new RUserSch();
			userSch.setIdSch(sTaskSchedule.getExecutorId());
			sTaskSchedule.setExecutor(rUserService.find(ExpressionQuery.buildQueryAll().addAnnotionExpression(userSch)).get(0));
			SCustomerSch customerSch = new SCustomerSch();
			customerSch.setIdSch(sTaskSchedule.getCustomerId());
			sTaskSchedule.setsCustomers(SCustomerService.find(ExpressionQuery.buildQueryAll().addAnnotionExpression(customerSch)));
			//添加图片链接
			SysUploadSch sysUploadSch = new SysUploadSch();
			sysUploadSch.setModuleIdSch("taskDetail");
			sysUploadSch.setDataIdSch(Integer.toString(sTaskSchedule.getId()));
			List<SysUpload> sysUploads = sysUploadService.find(ExpressionQuery.buildQueryAll().addAnnotionExpression(sysUploadSch));
			List<String> liveSituationUrl = new ArrayList<>();
		    List<String> processResultUrl = new ArrayList<>();
		    List<String> visiteRecordUrl = new ArrayList<>();
			for (SysUpload sysUpload : sysUploads) {
				if (sysUpload.getFuncId().equals("processResult")) {
					processResultUrl.add(sysUpload.getFilefullpath());
				}
				if (sysUpload.getFuncId().equals("liveSituation")) {
					liveSituationUrl.add(sysUpload.getFilefullpath());
				}
				if (sysUpload.getFuncId().equals("visiteRecord")) {
					visiteRecordUrl.add(sysUpload.getFilefullpath());
				}
				sTaskSchedule.setLiveSituationUrl(liveSituationUrl);
				sTaskSchedule.setProcessResultUrl(processResultUrl);
				sTaskSchedule.setVisiteRecordUrl(visiteRecordUrl);
			}
		}
		
		} catch (Exception e) {
			e.printStackTrace();
		}
		return Result;
	}

	//条件查询分页操作
		@RequestMapping("/listFinishedTaskSchedule.do")
		public @ResponseBody
		GridResult listFinishedTaskSchedule(STaskScheduleSch searchEntitySch) throws UnsupportedEncodingException {
			if (searchEntitySch.getStatusSch()!=null) {
				searchEntitySch.setStatusSch(URLDecoder.decode(searchEntitySch.getStatusSch(), "UTF-8"));
			}
			DefaultGridResult Result= (DefaultGridResult) this.query(searchEntitySch);
			List<STaskSchedule> taskSchedules = (List<STaskSchedule>) Result.getRows();
			Result.setList(taskSchedules);
			for (STaskSchedule sTaskSchedule : taskSchedules) {
				RUserSch userSch =new RUserSch();
				userSch.setIdSch(sTaskSchedule.getExecutorId());
				sTaskSchedule.setExecutor(rUserService.find(ExpressionQuery.buildQueryAll().addAnnotionExpression(userSch)).get(0));
				SCustomerSch customerSch = new SCustomerSch();
				customerSch.setIdSch(sTaskSchedule.getCustomerId());
				sTaskSchedule.setsCustomers(SCustomerService.find(ExpressionQuery.buildQueryAll().addAnnotionExpression(customerSch)));
				//添加图片链接
				SysUploadSch sysUploadSch = new SysUploadSch();
				sysUploadSch.setModuleIdSch("taskDetail");
				sysUploadSch.setDataIdSch(Integer.toString(sTaskSchedule.getId()));
				List<SysUpload> sysUploads = sysUploadService.find(ExpressionQuery.buildQueryAll().addAnnotionExpression(sysUploadSch));
				List<String> liveSituationUrl = new ArrayList<>();
			    List<String> processResultUrl = new ArrayList<>();
			    List<String> visiteRecordUrl = new ArrayList<>();
				for (SysUpload sysUpload : sysUploads) {
					if (sysUpload.getFuncId().equals("processResult")) {
						processResultUrl.add(sysUpload.getFilefullpath());
					}
					if (sysUpload.getFuncId().equals("liveSituation")) {
						liveSituationUrl.add(sysUpload.getFilefullpath());
					}
					if (sysUpload.getFuncId().equals("visiteRecord")) {
						visiteRecordUrl.add(sysUpload.getFilefullpath());
					}
					sTaskSchedule.setLiveSituationUrl(liveSituationUrl);
					sTaskSchedule.setProcessResultUrl(processResultUrl);
					sTaskSchedule.setVisiteRecordUrl(visiteRecordUrl);
				}
			}
			
			return Result;
		}
	//条件查询并返回所有记录
	@RequestMapping("/listAllSTaskSchedule.do")
    public @ResponseBody Object listAllSTaskSchedule(STaskSchedule entity) throws UnsupportedEncodingException {
		
		DefaultGridResult Result= new DefaultGridResult(); 
		List<STaskSchedule> taskSchedules = this.getService().getTaskSchduleTodo(entity);
		Result.setList(taskSchedules);
		try {
			for (STaskSchedule sTaskSchedule : taskSchedules) {
				RUserSch userSch =new RUserSch();
				userSch.setIdSch(sTaskSchedule.getExecutorId());
				sTaskSchedule.setExecutor(rUserService.find(ExpressionQuery.buildQueryAll().addAnnotionExpression(userSch)).get(0));
				SCustomerSch customerSch = new SCustomerSch();
				customerSch.setIdSch(sTaskSchedule.getCustomerId());
				sTaskSchedule.setsCustomers(SCustomerService.find(ExpressionQuery.buildQueryAll().addAnnotionExpression(customerSch)));
				//添加图片链接
				SysUploadSch sysUploadSch = new SysUploadSch();
				sysUploadSch.setModuleIdSch("taskDetail");
				sysUploadSch.setDataIdSch(Integer.toString(sTaskSchedule.getId()));
				List<SysUpload> sysUploads = sysUploadService.find(ExpressionQuery.buildQueryAll().addAnnotionExpression(sysUploadSch));
				List<String> liveSituationUrl = new ArrayList<>();
			    List<String> processResultUrl = new ArrayList<>();
			    List<String> visiteRecordUrl = new ArrayList<>();
				for (SysUpload sysUpload : sysUploads) {
					if (sysUpload.getFuncId().equals("processResult")) {
						processResultUrl.add(sysUpload.getFilefullpath());
					}
					if (sysUpload.getFuncId().equals("liveSituation")) {
						liveSituationUrl.add(sysUpload.getFilefullpath());
					}
					if (sysUpload.getFuncId().equals("visiteRecord")) {
						visiteRecordUrl.add(sysUpload.getFilefullpath());
					}
					sTaskSchedule.setLiveSituationUrl(liveSituationUrl);
					sTaskSchedule.setProcessResultUrl(processResultUrl);
					sTaskSchedule.setVisiteRecordUrl(visiteRecordUrl);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return Result;
    }

    //获取详细信息
	@RequestMapping("/getSTaskScheduleById.do")
    public @ResponseBody STaskSchedule getSTaskScheduleById(STaskSchedule entity) {
        return this.getService().get(entity.getId());
    }

 	

}